const OpenAI = require("openai");
import store from '@/store/index'

const openai = new OpenAI({
    apiKey: store.state.app.apiKey,
    baseURL: store.state.app.baseUrl,
    dangerouslyAllowBrowser:true
});
let abortController = new AbortController();
async function getResponse(messages) {
    openai.baseURL = store.state.app.baseUrl;
    openai.apiKey = store.state.app.apiKey;
    console.log(store.state.app.baseUrl,store.state.app.activeModel)
    abortController = new AbortController();
    try {
        const completion = await openai.chat.completions.create({
            model: store.state.app.activeModel,
            messages: messages,
            stream: true,
            stream_options: {
                include_usage: true
            },
            enable_thinking: true,
            max_tokens:4096
        }, {
            signal: abortController.signal // 传入中断信号
        });
        store.commit('app/setIsMessageDone',false)

        let fullContent = "";
        let reasoningContent = "";
        for await (const chunk of completion) {
            // 如果stream_options.include_usage为true，则最后一个chunk的choices字段为空数组，需要跳过（可以通过chunk.usage获取 Token 使用量）
            if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
                if (chunk.choices[0].delta.content){
                    fullContent = fullContent + chunk.choices[0].delta.content;
                    store.commit('app/setNowMessage',fullContent)
                }else if (chunk.choices[0].delta.reasoning_content){
                    reasoningContent = reasoningContent + chunk.choices[0].delta.reasoning_content;
                    store.commit('app/setNowReasoningMessage',reasoningContent)
                }
            }
            if (chunk.usage){
                console.log(chunk.usage)
            }
            if (store.state.app.stopCommand){
                store.dispatch('app/stopMsg',false)
                abortController.abort();
            }
        }
        return {fullContent,reasoningContent};
    } catch (error) {
        console.error("Error fetching response:", error);
        throw error;  // 重新抛出异常以便上层处理
    }
}
let prompt = `你是一位专为开发者设计的 智能代码助手，名为 ucoder。你的核心职责是帮助开发者高效完成项目开发，提供精准的代码提示、问题解答和最佳实践建议。
    ### 核心身份
    - **角色**：专业的开发顾问
    - **专长领域**：
      - HTML5/CSS3/JavaScript/TypeScript
      - Vue.js（2.x/3.x）及 uni-app 框架
      - 移动端混合开发（Android/iOS）
      - 微信小程序/支付宝小程序等跨平台开发
      - HbuilderX 特色功能（如真机调试、云打包等）
    ### 行为准则
    1. **响应风格**：
       - 使用简洁、专业的开发者语言
       - 代码示例必须完整且可直接运行
       - 复杂概念采用分步骤解释
       - 优先展示最符合 Hbuilder 生态的解决方案  
    2. **交互原则**：
   - 主动询问模糊需求的细节（如未说明的框架版本）
   - 对不确定的回答明确标注"建议参考"
   - 危险操作（如删除文件）必须二次确认
   - 超出能力范围时引导至官方文档 
   ### 技术响应
    请使用markdown格式回复
`
const systemMessages = [
    {
        "role": "system",
        "content": prompt
    }
];

export async function sendMessage(message){
    store.commit('app/setRequestStatus',true)
    let msgs = JSON.parse(JSON.stringify(store.state.app.sendMessages))

    let smsg = { role: "user", content: message }
    msgs.push(smsg)
    store.commit('app/setSendMessages',smsg)
    store.commit('app/setChatHistoryMessage', {...smsg, status:1})

    try {
        let pjInfo = store.state.app.projectInfo||{}
        systemMessages[0].content +=`
            ### 当前已激活正在编辑的项目信息
               - 项目名称：${pjInfo.workspaceFolder ? pjInfo.workspaceFolder.name : 'unknown'}
               - 项目类型：${pjInfo.workspaceFolder ? pjInfo.workspaceFolder.nature : 'unknown'}
               - 文件语言：${pjInfo.languageId}
               - 文件名称：${pjInfo.fileName}
        `
        let response = await getResponse([...systemMessages,...msgs]);
        if (!response)response={fullContent:'',reasoningContent:''}
        store.commit('app/setRequestStatus',false)
        store.commit('app/setIsMessageDone',true)
        store.commit('app/setNowMessage','')
        store.commit('app/setNowReasoningMessage','')

        let rmsg = { role: "assistant", content: response.fullContent }
        // 加入发送消息列表
        store.commit('app/setSendMessages',rmsg)
        // 加入历史消息列表
        store.commit('app/setChatHistoryMessage', {...rmsg,reasoningContent:response.reasoningContent})

    } catch (error) {
        store.commit('app/setRequestStatus',false)
        store.commit('app/setIsMessageDone',true)
        store.commit('app/setNowMessage','')
        store.commit('app/setNowReasoningMessage','')

        store.commit('app/setSendMessageErr')
        console.error("获取响应时发生错误:", error);
        if (store.state.app.requestErrCount<3){
            store.commit('app/setRequestErrCount',store.state.app.requestErrCount+1)
        }else{
            store.commit('app/setRequestErrCount',0)
            store.commit('app/setChatHistoryMessage',{ role: "assistant", content: "获取响应时发生错误:"+JSON.stringify(error) })
        }
    }

}

export async function handleCode(code,msg){

    if (store.state.app.requestStatus)return

    store.commit('app/setRequestStatus',true)
    let msgs = JSON.parse(JSON.stringify(store.state.app.sendMessages))

    let smsg = { role: "user", content: code+'/n'+msg }
    msgs.push(smsg)
    store.commit('app/setSendMessages',smsg)
    store.commit('app/setChatHistoryMessage', {role: "user", content: msg, status:1})

    try {
        let pjInfo = store.state.app.projectInfo||{}
        systemMessages[0].content +=`
            ### 当前项目信息
               - 项目名称：${pjInfo.workspaceFolder ? pjInfo.workspaceFolder.name : 'unknown'}
               - 项目类型：${pjInfo.workspaceFolder ? pjInfo.workspaceFolder.nature : 'unknown'}
               - 文件语言：${pjInfo.languageId}
               - 文件名称：${pjInfo.fileName}
        `
        let response = await getResponse([...systemMessages,...msgs]);
        if (!response)response={fullContent:'',reasoningContent:''}

        store.commit('app/setRequestStatus',false)
        store.commit('app/setIsMessageDone',true)
        store.commit('app/setNowMessage','')
        store.commit('app/setNowReasoningMessage','')

        let rmsg = { role: "assistant", content: response.fullContent }
        // 加入发送消息列表
        store.commit('app/setSendMessages',rmsg)
        // 加入历史消息列表
        store.commit('app/setChatHistoryMessage',{...rmsg,reasoningContent:response.reasoningContent})

    } catch (error) {
        store.commit('app/setRequestStatus',false)
        store.commit('app/setIsMessageDone',true)
        store.commit('app/setNowMessage','')
        store.commit('app/setNowReasoningMessage','')

        store.commit('app/setSendMessageErr')
        console.error("获取响应时发生错误:", error);
        if (store.state.app.requestErrCount<3){
            store.commit('app/setRequestErrCount',store.state.app.requestErrCount+1)
        }else{
            store.commit('app/setRequestErrCount',0)
            store.commit('app/setChatHistoryMessage',{ role: "assistant", content: "获取响应时发生错误:"+JSON.stringify(error) })
        }
    }

}

